/**
 * 封装记住密码方法
 */

import CryptoJS from "crypto-js";

const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF");
const iv = CryptoJS.enc.Utf8.parse("ABCDEF1234123412");

// 解密方法
function Decrypt(word) {
    let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
};

// 加密方法
function Encrypt(word) {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString().toUpperCase();
};

// 设置cookie
export const setCookie=(userName,password,exdays,that)=>{
    // 加密账号密码
    let encryptUserName=Encrypt(userName);
    let encryptPassword=Encrypt(password);
    let exdate=new Date();
    exdate.setTime(exdate.getTime() + 24*60*60*1000*exdays); //保存的天数
    window.document.cookie="username=="+encryptUserName+";path=/;expires="+exdate.toGMTString();
    window.document.cookie="password=="+encryptPassword+";path=/;expires="+exdate.toGMTString();
};

// 读取cookie
export const getCookie=(that)=>{
    if(document.cookie.length > 0 && document.cookie.includes("username==")){
        const info={
            "username":Decrypt(that.$Qilin.Storage.getValueCookie("username",2)),
            "password":Decrypt(that.$Qilin.Storage.getValueCookie("password",2))
        };
        return info;
    };
};

// 清除cookie
export const clearCookie=()=>{
    setCookie("","",-1);
};